/*
 * User: DuYu
 * Date: 04/14/14
 * To change this template use File
 */

(function($) {
    $.fn.extend({

        readonly:function(options){
            options = $.extend({}, options);
            return this.each(function () {
                if($(this).is("form")){$(this).attr("action","");}
                $(this).find("form").attr("action","");

                $(this).find("select").each(function(){
                    $(this).replaceWith("<input type='text' value='"+$(this).find("option:selected").text()+"'>");
                });

                $(this).find(":checkbox").each(function(){
                    var _id = $(this).attr("id");
                    if(_id){
                        var _label = $("label[for='"+_id+"']");
                        if(_label.length>0){
                            $(this).remove();
                            if($(this).is(":checked")){
                                if(_label.prev("label").length!=0)_label.text(","+_label.text())
                            }else{
                                _label.remove();
                            }
                        }
                    }
                });

                $(this).find(":radio").each(function(){
                    var _id = $(this).attr("id");
                    if(_id){
                        var _label = $("label[for='"+_id+"']");
                        if(_label.length>0){
                            $(this).remove();
                            if(!$(this).is(":checked")){
                                _label.remove();
                            }
                        }
                    }
                });

                $(this).find("input[type=text]").attr("readonly","readonly").css("border","0").unbind();
                $(this).find("textarea").attr("readonly","readonly").css("border","0");

                $(this).find("input[type=checkbox]").click(function(){this.checked = !this.checked;});
                $(this).find("input[type=radio]").click(function(){this.checked = !this.checked;});
                $(this).find("input[type=file]").remove();
                $(this).find("input[type=reset]").remove();
                $(this).find("input[type=submit]").remove();
                $(this).find(":button").not(".btn_back").remove();

                $(this).find("input[type=checkbox]").attr("disabled","true");
                $(this).find("input[type=radio]").attr("disabled","true");
                $(this).find("select").attr("disabled","true").css("border","0");


            });
        },

        autoMatch:function(data,options){
            options = $.extend({}, options);
            if(options.prefix !=undefined && options.prefix!=null){
                options.prefix = options.prefix +".";
            }else{
                options.prefix = "";
            }

            return this.each(function () {
                for(var _p in data){
                    var _val = data[_p];
                    if(_val==null)_val = "";

                    if((typeof _val == 'object') && _val.constructor == Object){
                        $(this).autoMatch(_val,{prefix:_p});
                        continue;
                    }
                    $(this).find("*[name='"+options.prefix+_p+"']").each(function(){
                        if($.isArray(_val)){
                            for(var _a in _val){
                                if($(this).is("select")){
                                    $(this).find("option[value="+_val[_a]+"]").attr("selected",true).trigger("change");
                                }

                                if($(this).is(":checkbox")){
                                    if(_val[_a] == $(this).val())
                                        $(this).attr("checked",true).trigger("change");
                                }
                            }

                        }else{
                            if($(this).is(":text") || $(this).is(":hidden")){
                                $(this).val(_val);
                            }

                            if($(this).is(":checkbox")){
                                if(_val == $(this).val()){
                                    $(this).attr("checked",true).trigger("change");
                                }else if(_val){
                                    $(this).attr("checked",_val).trigger("change");
                                }

                            }

                            if($(this).is(":radio")){
                                if(_val == $(this).val()){
                                    $(this).attr("checked",true).trigger("change");
                                }
                            }

                            if($(this).is("textarea")){
                                $(this).text(_val);
                            }

                            if($(this).is("select")){
                                $(this).find("option[value="+_val+"]").attr("selected",true).trigger("change");
                            }
                        }


                    })
                }

            });
        },

        serializeObject : function() {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [ o[this.name] ];
                    }
                    o[this.name].push($.trim(this.value) || '');
                } else {
                    o[this.name] = $.trim(this.value) || '';
                }
            });
            return o;
        },

        form2json : function(){

            function paramString2obj (serializedParams) {
                var obj={};
                function evalThem (str) {
                    var attributeName = str.split("=")[0];
                    var attributeValue = str.split("=")[1];
                    if(!attributeValue){
                        return ;
                    }

                    var array = attributeName.split(".");
                    for (var i = 1; i < array.length; i++) {
                        var tmpArray = [];
                        tmpArray.push("obj");
                        for (var j = 0; j < i; j++) {
                            tmpArray.push(array[j]);
                        }
                        var evalString = tmpArray.join(".");
                        // alert(evalString);
                        if(!eval(evalString)){
                            eval(evalString+"={};");
                        }
                    }

                    eval("obj."+attributeName+"='"+attributeValue+"';");

                }

                var properties = serializedParams.split("&");
                for (var i = 0; i < properties.length; i++) {
                    evalThem(properties[i]);
                }

                return obj;
            }

            var serializedParams = this.serialize();
            return paramString2obj(serializedParams);
    //    	return JSON.stringify(obj);
        }
    });


    $.extend({
        prompt: function (_msg, _title) {
            if (_msg==undefined || _msg==null)_msg = "";
            if (_title == undefined || _title == null)_title = '提示';

            var _prompt = $("#_common_prompt");
            if (_prompt.length == 0) {
                _prompt = $("<div id='_common_prompt'></div>");
                _prompt.appendTo("body")
                    .dialog({
                        modal: true,
                        autoOpen: false,
                        bgiframe: true,
                        resizable: false,
                        draggable: false,
                        width: 200,
                        height: 200
                    });
            }
            _prompt.attr("title", _title).empty().append("<span>" + _msg + "</span>")
                .dialog("option",{title:_title});
            return _prompt.dialog("open");
        },

        confirm: function(_fun,_param,_msg, _title) {
            if (_param==undefined || _param==null)_param = "";
            if (_msg==undefined || _msg==null)_msg = "确定删除?";
            if (_title == undefined || _title == null)_title = '提示';

            var _prompt = $("#_common_confirm");
            if (_prompt.length == 0) {
                _prompt = $("<div id='_common_confirm'></div>");
                _prompt.appendTo("body")
                    .dialog({
                        modal: true,
                        autoOpen: false,
                        bgiframe: true,
                        resizable: false,
                        draggable: false,
                        width: 200,
                        height: 200
                    });
            }
            _prompt.attr("title", _title).empty().append("<span>" + _msg + "</span>")
                .dialog("option",{title:_title})
                .dialog( "option", "buttons", {
                    "确定": function () {
                        //$("#_common_confirm").data("_param");
                        if(_fun && _param){
                            _fun(_param);
                        }else if(_fun){
                            _fun();
                        }
                        $(this).dialog("close");
                    },
                    "取消": function () {
                        $(this).dialog("close");
                    }
                } );
            return _prompt.dialog("open");
        },

        actionDialog: function(_fun,_param,_obj, _title) {
            if (_param==undefined || _param==null)_param = "";
            if (_obj==undefined || _obj==null)_obj = $("<div></div>");
            if (_title == undefined || _title == null)_title = '提示';

            var _prompt = $("#_common_action_dialog");
            if (_prompt.length == 0) {
                _prompt = $("<div id='_common_action_dialog'></div>");
                _prompt.appendTo("body")
                    .dialog({
                        modal: true,
                        autoOpen: false,
                        bgiframe: true,
                        resizable: false,
                        draggable: false,
                        width: 320,
                        height: 200
                    });
            }
            _prompt.attr("title", _title).empty().append(_obj)
                .dialog("option",{title:_title})
                .dialog( "option", "buttons", {
                    "确定": function () {
                        if(_fun && _param){
                            _fun(_param);
                        }else if(_fun){
                            _fun();
                        }
                        $(this).dialog("close");
                    },
                    "取消": function () {
                        $(this).dialog("close");
                    }
                } );
            _obj.show();
            return _prompt.dialog("open");
        },

        linkAlert: function(_msg,_onclick, _title) {
            if (_msg==undefined || _msg==null)_msg = "";
            if (_title == undefined || _title == null)_title = '提示';

            var _prompt = $("#_common_link_alert");
            if (_prompt.length == 0) {
                _prompt = $("<div id='_common_link_alert'></div>");
                _prompt.appendTo("body")
                    .dialog({
                        bgiframe: true,
                        resizable: false,
                        draggable:false,
                        width: 200,
                        height: 200,
                        position: ['right', 'bottom']
                    });
            }
            var _link = $("<a href='javascript:void(0)'></a>").append(_msg);
            _link.click(function(){
                _onclick();
                $("#_common_link_alert").dialog("close");
            });
            _prompt.empty().append(_link)
                .dialog("option",{title:_title});
            return _prompt.dialog("open");
        },

        handleError: function( s, xhr, status, e ) 		{
        // If a local callback was specified, fire it
            if ( s.error ) {
                s.error.call( s.context || s, xhr, status, e );
            }

            // Fire the global callback
            if ( s.global ) {
                (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
            }
        }
    });


})(jQuery);


